package com.gd.iot.energy.service.systemadmin.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gd.iot.energy.code.ResponseCode;
import com.gd.iot.energy.consts.SystemConsts;
import com.gd.iot.energy.dao.systemadmin.AreaArchivesPOMapper;
import com.gd.iot.energy.dao.systemadmin.EquipCollectPOMapper;
import com.gd.iot.energy.exception.MyException;
import com.gd.iot.energy.po.datamanage.EquipInstructionPO;
import com.gd.iot.energy.po.datamanage.EquipInstructionPOWithBLOBs;
import com.gd.iot.energy.po.datamanage.EquipInstructiontreePO;
import com.gd.iot.energy.po.systemadmin.AreaArchivesPO;
import com.gd.iot.energy.po.systemadmin.EquipCollectPO;
import com.gd.iot.energy.po.systemadmin.EquipConcentPO;
import com.gd.iot.energy.po.systemadmin.EquipmentmodelPO;
import com.gd.iot.energy.pojo.common.vo.ColumnVO;
import com.gd.iot.energy.pojo.common.vo.PageVO;
import com.gd.iot.energy.pojo.datamanage.vo.RemotePageVO;
import com.gd.iot.energy.pojo.systemadmin.dto.ArchivesSaveDTO;
import com.gd.iot.energy.pojo.systemadmin.dto.AreaArchivesSaveDTO;
import com.gd.iot.energy.pojo.systemadmin.dto.AreaOrganizationSaveDTO;
import com.gd.iot.energy.pojo.systemadmin.vo.ArchivesPageVO;
import com.gd.iot.energy.pojo.systemadmin.vo.ArchivesVO;
import com.gd.iot.energy.pojo.systemadmin.vo.AreaOrganizationVO;
import com.gd.iot.energy.pojo.systemadmin.vo.EnumVO;
import com.gd.iot.energy.service.datamanage.EquipInstructionService;
import com.gd.iot.energy.service.datamanage.EquipInstructionTreeService;
import com.gd.iot.energy.service.systemadmin.AreaArchivesService;
import com.gd.iot.energy.service.systemadmin.AreaOrganizationService;
import com.gd.iot.energy.service.systemadmin.EquipConcentService;
import com.gd.iot.energy.service.systemadmin.EquipmentmodelService;
import com.gd.iot.energy.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author kris
 * @date 2020/8/28 0028 11:22
 */
@Service
public class AreaArchivesServiceImpl extends ServiceImpl<AreaArchivesPOMapper, AreaArchivesPO> implements AreaArchivesService {

    /**
     * 字段配置文件
     */
    private static final String REMOTE_LIST_COLUMN_FILE_NAME = "datamanage/remote_control_list.column";

    @Resource
    private AreaArchivesPOMapper areaArchivesPOMapper;

    @Resource
    private AreaOrganizationService areaOrganizationService;

    @Resource
    private EquipCollectPOMapper equipCollectPOMapper;

    @Resource
    private EquipConcentService equipConcentService;

    @Autowired
    private EquipmentmodelService equipmentmodelService;

    @Autowired
    private EquipInstructionService equipInstructionService;

    @Autowired
    private EquipInstructionTreeService equipInstructionTreeService;

    /**
     * 表头文件
     */
    private static final String ARCHIVES_LIST_COLUMN_FILE_NAME = "systemadmin/archives_list.column";

    @Override
    public PageVO<RemotePageVO> getCurrentUserArchivesPage(String customerName, String customerPhone, Integer areaId,
                                                           Integer pageSize, Integer pageNum, String orderColumn, String orderType) {
        PageVO<RemotePageVO> pageVO = new PageVO<>();
        pageVO.setPageSize(pageSize);
        pageVO.setPageNum(pageNum);

        //表头
        List<ColumnVO> columns = CustomColumnUtil.getColumn(REMOTE_LIST_COLUMN_FILE_NAME);
        pageVO.setColumns(columns);

        List<Integer> currentUserEquipments = CurrentUserUtil.getCurrentUserEquipments();
        boolean isSuperAdmin = CurrentUserUtil.isSuperAdmin();
        if (currentUserEquipments.isEmpty() && !isSuperAdmin) {
            pageVO.setTotal(0L);
            pageVO.setData(new ArrayList<>(0));
            return pageVO;
        }

        IPage<AreaArchivesPO> page = new Page<>(pageNum, pageSize);
        QueryWrapper<AreaArchivesPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del", SystemConsts.BooleanEnum.FALSE.value);
        EnergyTypeUtil.injectEnergyTypeWrapper(queryWrapper);
        if (areaId != null) {
            List<Long> allChildAreaIds = areaOrganizationService.getAllChildAreaIds(areaId);
            if (CollUtil.isNotEmpty(allChildAreaIds)) {
                queryWrapper.in("measure_area_org", allChildAreaIds);
            }
        }
        if (StrUtil.isNotBlank(customerName)) {
            queryWrapper.like("customer_name", customerName.trim());
        }
        if (StrUtil.isNotBlank(customerPhone)) {
            queryWrapper.like("customer_phone", customerPhone.trim());
        }
        if (!isSuperAdmin) {
            queryWrapper.in("id", currentUserEquipments);
        }
        if (StrUtil.isNotBlank(orderColumn) && StrUtil.isNotBlank(orderType)) {
            orderColumn = CustomStrUtil.humpToLine(orderColumn);
            queryWrapper.orderBy(true, orderType.equals(SystemConsts.OrderType.ASC.value), orderColumn);
        }
        EnergyTypeUtil.injectEnergyTypeWrapper(queryWrapper);
        IPage<AreaArchivesPO> areaArchivesPOPage = areaArchivesPOMapper.selectPage(page, queryWrapper);
        List<RemotePageVO> roleVOList = convertToRemotePageVOList(areaArchivesPOPage.getRecords());
        pageVO.setData(roleVOList);
        pageVO.setTotal(areaArchivesPOPage.getTotal());
        pageVO.setPages(areaArchivesPOPage.getPages());
        return pageVO;
    }

    @Override
    public void open(String id) {
        AreaArchivesPO archives = getById(id);

        if (archives == null) {
            throw new MyException(ResponseCode.OPEN_VALVE_FAIL);
        }
        if (archives.getMeasureEquipCollect() == null) {
            throw new MyException(ResponseCode.OPEN_VALVE_FAIL_NO_COLLECT);
        }
        EquipCollectPO equipCollectPO = equipCollectPOMapper.selectById(archives.getMeasureEquipCollect());
        if (equipCollectPO == null) {
            throw new MyException(ResponseCode.OPEN_VALVE_FAIL_NO_COLLECT);
        }
        if (equipCollectPO.getEquipConcent() == null) {
            throw new MyException(ResponseCode.OPEN_VALVE_FAIL_NO_CONCERT);
        }

        EquipConcentPO equipConcentPO = equipConcentService.getById(equipCollectPO.getEquipConcent());
        if (equipConcentPO == null) {
            throw new MyException(ResponseCode.OPEN_VALVE_FAIL_NO_CONCERT);
        }

        final String phone = equipConcentPO.getConncentSerialnumber();

        final String collectNumber = equipCollectPO.getCollectSerialnumber();
        EquipInstructionPOWithBLOBs equipInstruction = equipInstructionService.getInstructionByConcentPhone(collectNumber, phone);

        if (equipInstruction == null) {
            throw new MyException(ResponseCode.OPEN_VALVE_FAIL_EQUIP_OFFLINE);
        }
        final String collectorAddress = equipCollectPO.getCollectSerialnumber();
        final String sessionId = equipInstruction.getSessionId();

        //TODO 发指令
    }

    @Override
    public void close(String id) {
        AreaArchivesPO archives = getById(id);

        if (archives == null) {
            throw new MyException(ResponseCode.CLOSE_VALVE_FAIL);
        }
        if (archives.getMeasureEquipCollect() == null) {
            throw new MyException(ResponseCode.CLOSE_VALVE_FAIL_NO_COLLECT);
        }
        EquipCollectPO equipCollectPO = equipCollectPOMapper.selectById(archives.getMeasureEquipCollect());
        if (equipCollectPO == null) {
            throw new MyException(ResponseCode.CLOSE_VALVE_FAIL_NO_COLLECT);
        }
        if (equipCollectPO.getEquipConcent() == null) {
            throw new MyException(ResponseCode.CLOSE_VALVE_FAIL_NO_CONCERT);
        }

        EquipConcentPO equipConcentPO = equipConcentService.getById(equipCollectPO.getEquipConcent());
        if (equipConcentPO == null) {
            throw new MyException(ResponseCode.CLOSE_VALVE_FAIL_NO_CONCERT);
        }

        final String phone = equipConcentPO.getConncentSerialnumber();

        final String collectNumber = equipCollectPO.getCollectSerialnumber();
        EquipInstructionPOWithBLOBs equipInstruction = equipInstructionService.getInstructionByConcentPhone(collectNumber, phone);

        if (equipInstruction == null) {
            throw new MyException(ResponseCode.CLOSE_VALVE_FAIL_EQUIP_OFFLINE);
        }
        final String collectorAddress = equipCollectPO.getCollectSerialnumber();
        final String sessionId = equipInstruction.getSessionId();

        //TODO 发指令
    }

    @Override
    public void multiOperate(List<Long> ids, String state) {

        if (ids == null || ids.isEmpty()) {
            throw new MyException(ResponseCode.PARAMETER_REQUIRED);
        }
        AreaArchivesPO areaArchives = null;
        int failSum = 0;
        int successSum = 0;
        StringBuilder errorMessage = new StringBuilder();
        for (Long id : ids) {

            areaArchives = getById(id);
            if (areaArchives == null) {
                ++failSum;
                errorMessage.append("档案不存在,");
            } else {
                final Long sysconfigEquipmentModelId = areaArchives.getSysconfigEquipmentModel();
                final EquipmentmodelPO equipmentModel = equipmentmodelService.getById(sysconfigEquipmentModelId);
                if (equipmentModel == null) {
                    ++failSum;
                    errorMessage.append("设备型号不存在,");
                } else {
                    EquipInstructiontreePO tree = equipInstructionTreeService.getByState(sysconfigEquipmentModelId, state);

                    if (tree == null) {
                        ++failSum;
                        errorMessage.append("无相关开关阀指令,");
                    } else {
                        if (tree.getId() == 18L || tree.getId() == 19L) {
                            final EquipConcentPO ec = equipConcentService.getById(areaArchives.getMeasureEquipConcent());
                            final EquipCollectPO ecc = equipCollectPOMapper.selectById(areaArchives.getMeasureEquipCollect());
                            if (ec == null) {
                                throw new MyException(ResponseCode.NO_CONCERT);
                            }
                            final EquipInstructionPO equipInstruction = equipInstructionService.getInstructionByConcentPhone(ecc.getCollectSerialnumber(), ec.getConncentSerialnumber());
                            if (equipInstruction == null) {
                                throw new MyException(ResponseCode.CONCERT_OFFLINE);
                            }

                            //TODO iot 相关
//                            final Channel channel = SocketServer.channels.get(equipInstruction.getSessionId());

//                            if (channel == null) {
//                                throw new MyException(ResponseCode.CONCERT_OFFLINE);
//                            }
                        }
                        final String treeMethod = tree.getTreeMethod();
                        final JSONObject jsonParams = new JSONObject();
                        String idStr = "";
                        try {
                            final Object obj = SpringUtil.getBean(tree.getTreeAction());
                            idStr = (String) obj.getClass().getDeclaredMethod(treeMethod, EquipInstructiontreePO.class, EquipmentmodelPO.class, AreaArchivesPO.class, JSONObject.class).invoke(obj, tree, equipmentModel, areaArchives, jsonParams);
                        } catch (IllegalAccessException | SecurityException | NoSuchMethodException | IllegalArgumentException | InvocationTargetException e) {
                            log.error(e.getMessage(), e);
                        }
                        if (id == null || "".equals(idStr)) {
                            ++failSum;
                        } else {
                            ++successSum;
                        }
                    }
                }
            }
        }
        if (failSum > 0 && successSum == 0) {
            throw new MyException("操作成功,其中失败" + failSum + "条" + ",成功" + successSum + "条," + errorMessage);
        }
    }

    @Override
    public AreaArchivesPO getByDeviceId(String deviceId) {
//        QueryWrapper<AreaArchivesPO> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("customer_serialnumber",deviceId);
//        queryWrapper.eq("is_del", SystemConsts.BooleanEnum.FALSE.value);
//        EnergyTypeUtil.injectEnergyTypeWrapper(queryWrapper);
//        return areaArchivesPOMapper.selectOne(queryWrapper);

        return null;
    }

    @Override
    public AreaArchivesPO getByImei(String imei) {
        QueryWrapper<AreaArchivesPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("nbonet_net_imei", imei);
        queryWrapper.eq("is_del", SystemConsts.BooleanEnum.FALSE.value);
        EnergyTypeUtil.injectEnergyTypeWrapper(queryWrapper);
        return areaArchivesPOMapper.selectOne(queryWrapper);
    }

    /**
     * vo 转dto
     *
     * @param records
     * @return
     */
    private List<RemotePageVO> convertToRemotePageVOList(List<AreaArchivesPO> records) {

        List<Long> areas = records.stream().map(AreaArchivesPO::getMeasureAreaOrg).collect(Collectors.toList());
        Map<Long, String> areaNamesMap = areaOrganizationService.getAreaNamesById(areas);

        List<RemotePageVO> res = new ArrayList<>(records.size());
        RemotePageVO remotePageVO;
        for (AreaArchivesPO record : records) {
            remotePageVO = new RemotePageVO();
            remotePageVO.setId(record.getId());
            remotePageVO.setAreaName(areaNamesMap.get(record.getMeasureAreaOrg()));
            remotePageVO.setCustomerName(record.getCustomerName());
            remotePageVO.setCustomerPhone(record.getCustomerPhone());
            remotePageVO.setCustomerSerialnumber(record.getCustomerSerialnumber());
            remotePageVO.setCustomerState(SystemConsts.AreaCustomerStateEnum.getValueNameByValue(record.getCustomerState()));
            remotePageVO.setEquipmentType(SystemConsts.EquipmentTypeEnum.getValueNameByValue(record.getEquipmentType()));
            remotePageVO.setValveState(SystemConsts.ValveType.getValueNameByValue(record.getValveState()));
            res.add(remotePageVO);
        }
        return res;
    }

    @Override
    public List<ArchivesVO> getArchivesVOs(Long areaOrg, String customerName) {
        QueryWrapper<AreaArchivesPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del", SystemConsts.BooleanEnum.FALSE.value);

        if (areaOrg != null) {
            List<Long> allChildAreaIds = areaOrganizationService.getAllChildAreaIds(BigDecimal.valueOf(areaOrg).intValue());
            if (CollUtil.isNotEmpty(allChildAreaIds)) {
                queryWrapper.in("measure_area_org", allChildAreaIds);
            }
        }

        if (StrUtil.isNotBlank(customerName)) {
            queryWrapper.like("customer_name", customerName);
        }
        EnergyTypeUtil.injectEnergyTypeWrapper(queryWrapper);
        List<AreaArchivesPO> areaArchivesPOS = areaArchivesPOMapper.selectList(queryWrapper);
        List<ArchivesVO> archivesVOS = new ArrayList<>(areaArchivesPOS.size());
        CustomBeanUtils.convertPojo(areaArchivesPOS, archivesVOS, ArchivesVO.class);
        return archivesVOS;
    }

    @Override
    public PageVO<ArchivesPageVO> getArchivesPageVOs(Long areaOrg, Integer filterType, String filterValue, Integer pageSize, Integer pageNo, String orderColumn, String orderType) {
        IPage<AreaArchivesPO> page = new Page<>(pageNo, pageSize);
        QueryWrapper<AreaArchivesPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del", SystemConsts.BooleanEnum.FALSE.value);

        if (!SystemConsts.ArchivesFilter.ALL.value.equals(filterType) && StrUtil.isNotBlank(filterValue)) {
            if (SystemConsts.ArchivesFilter.CUSTOMER_NAME.value.equals(filterType)) {
                queryWrapper.like("customer_name", filterValue.trim());
            } else if (SystemConsts.ArchivesFilter.CUSTOMER_SERIALNUMBER.value.equals(filterType)) {
                queryWrapper.like("customer_serialnumber", filterValue.trim());
            } else if (SystemConsts.ArchivesFilter.SERIALNUMBER.value.equals(filterType)) {
                queryWrapper.like("serialnumber", filterValue.trim());
            } else if (SystemConsts.ArchivesFilter.NBONET_NET_IMEI.value.equals(filterType)) {
                queryWrapper.like("nbonet_net_imei", filterValue.trim());
            } else if (SystemConsts.ArchivesFilter.NBONE_NET_DEVICE_ID.value.equals(filterType)) {
                queryWrapper.like("nbone_net_device_id", filterValue.trim());
            } else if (SystemConsts.ArchivesFilter.LORAWAN_DEVEUI.value.equals(filterType)) {
                queryWrapper.like("lorawan_deveui", filterValue.trim());
            }
        }

        if (areaOrg != null) {
            List<Long> allChildAreaIds = areaOrganizationService.getAllChildAreaIds(BigDecimal.valueOf(areaOrg).intValue());
            if (CollUtil.isNotEmpty(allChildAreaIds)) {
                queryWrapper.in("measure_area_org", allChildAreaIds);
            }
        }

        if (StrUtil.isNotBlank(orderColumn) && StrUtil.isNotBlank(orderType)) {
            orderColumn = CustomStrUtil.humpToLine(orderColumn);
            queryWrapper.orderBy(true, orderType.equals(SystemConsts.OrderType.ASC.value), orderColumn);
        }
        EnergyTypeUtil.injectEnergyTypeWrapper(queryWrapper);
        IPage<AreaArchivesPO> archivesPOIPage = areaArchivesPOMapper.selectPage(page, queryWrapper);
        PageVO<ArchivesPageVO> pageVO = new PageVO<>();
        pageVO.setPageSize(pageSize);
        pageVO.setPageNum(pageNo);
        List<ArchivesPageVO> treePageVOS = convertToArchivesPageVOList(archivesPOIPage.getRecords(), pageSize, pageNo);
        pageVO.setData(treePageVOS);
        pageVO.setTotal(archivesPOIPage.getTotal());
        pageVO.setPages(archivesPOIPage.getPages());

        //表头
        List<ColumnVO> columns = CustomColumnUtil.getColumn(ARCHIVES_LIST_COLUMN_FILE_NAME);
        pageVO.setColumns(columns);
        return pageVO;
    }

    /**
     * 对象转换
     *
     * @param records
     * @return
     */
    private List<ArchivesPageVO> convertToArchivesPageVOList(List<AreaArchivesPO> records, Integer pageSize, Integer pageNo) {
        List<AreaOrganizationVO> areaOrganizationVOs = areaOrganizationService.getAreaOrganizationVOs();
        Map<Long, String> collect = areaOrganizationVOs.stream().collect(
                Collectors.toMap(AreaOrganizationVO::getId, AreaOrganizationVO::getName, (key1, key2) -> key2));
        List<ArchivesPageVO> res = new ArrayList<>(records.size());
        ArchivesPageVO areaArchivesPageVO;

        long i = pageSize * (pageNo - 1) + 1;
        for (AreaArchivesPO record : records) {
            areaArchivesPageVO = new ArchivesPageVO();
            areaArchivesPageVO.setSerialNum(i);
            areaArchivesPageVO.setId(record.getId());
            areaArchivesPageVO.setCustomerName(record.getCustomerName());
            areaArchivesPageVO.setCustomerTypeName(SystemConsts.ArchivesCustomerTypeEnum.getDescNameByValue(record.getCustomerType()));
            areaArchivesPageVO.setCustomerSerialnumber(record.getCustomerSerialnumber());
            areaArchivesPageVO.setCustomerStateName(SystemConsts.ArchivesCustomerStateEnum.getDescNameByValue(record.getCustomerState()));
            areaArchivesPageVO.setSerialnumber(record.getSerialnumber());
            areaArchivesPageVO.setNboneNetDeviceId(record.getNboneNetDeviceId());
            areaArchivesPageVO.setNbonetNetImei(record.getNbonetNetImei());
            areaArchivesPageVO.setLorawanDeveui(record.getLorawanDeveui());
            areaArchivesPageVO.setCustomerUseStateName(SystemConsts.EnabledState.getValuenameByValue(record.getCustomerUseState()));
            areaArchivesPageVO.setValveStateName(SystemConsts.ValveStateEnum.getDescNameByValue(record.getValveState()));
            areaArchivesPageVO.setCustomerFee("￥ " + record.getCustomerFee());
            areaArchivesPageVO.setReading(record.getReading());

            res.add(areaArchivesPageVO);
            i++;
        }
        return res;
    }

    @Override
    public Long add(ArchivesSaveDTO archivesSaveDTO) {
        if (archivesSaveDTO.getCustomerName() == null ||
                StrUtil.isBlank(archivesSaveDTO.getSerialnumber())) {
            throw new MyException(ResponseCode.PARAMETER_REQUIRED);
        }

        //邮箱合法性校验，可以为空，不为空格式需符合要求
        if (StrUtil.isNotBlank(archivesSaveDTO.getCustomerEmail()) &&
                !CustomStrUtil.isEmail(archivesSaveDTO.getCustomerEmail())) {
            throw new MyException(ResponseCode.EMAIL_FORMAT_ERROR);
        }

        AreaArchivesPO areaArchivesPO = new AreaArchivesPO();
        areaArchivesPO.setCompanyId(0L);
        areaArchivesPO.setCreateDate(new Date());
        areaArchivesPO.setEnergyType(SystemConsts.EnergyTypeEnum.WATER.value);
        areaArchivesPO.setIsDel(SystemConsts.BooleanEnum.FALSE.value);
        areaArchivesPO.setModifyDate(new Date());
        areaArchivesPO.setOperatorId(1L);

        areaArchivesPO.setCollectChannel(archivesSaveDTO.getCollectChannel());
        areaArchivesPO.setControlValueAddress(archivesSaveDTO.getCustomerAddress());
        areaArchivesPO.setCustomerAddress(archivesSaveDTO.getCustomerAddress());
        areaArchivesPO.setCustomerCertificateNumber(archivesSaveDTO.getCustomerCertificateNumber());
        areaArchivesPO.setCustomerCertificateType(archivesSaveDTO.getCustomerCertificateType());
        areaArchivesPO.setCustomerEmail(archivesSaveDTO.getCustomerEmail());
        areaArchivesPO.setCustomerFee(archivesSaveDTO.getCustomerFee());
        areaArchivesPO.setCustomerName(archivesSaveDTO.getCustomerName());
        areaArchivesPO.setCustomerPassword(archivesSaveDTO.getCustomerAddress());
        areaArchivesPO.setCustomerPhone(archivesSaveDTO.getCustomerPhone());
        areaArchivesPO.setCustomerSerialnumber(archivesSaveDTO.getCustomerSerialnumber());
        areaArchivesPO.setCustomerState(archivesSaveDTO.getCustomerState());
        areaArchivesPO.setCustomerTel(archivesSaveDTO.getCustomerTel());
        areaArchivesPO.setCustomerType(archivesSaveDTO.getCustomerType());
        areaArchivesPO.setCustomerUseState(archivesSaveDTO.getCustomerUseState());
        areaArchivesPO.setHouseholdNum(archivesSaveDTO.getHouseholdNum());
        areaArchivesPO.setMeasureBillingType(archivesSaveDTO.getMeasureBillingType());
        areaArchivesPO.setMeasureControlType(archivesSaveDTO.getMeasureControlType());
        areaArchivesPO.setMeasureName(archivesSaveDTO.getMeasureName());
        areaArchivesPO.setMeasureOverdraftMoney(archivesSaveDTO.getMeasureOverdraftMoney());
        areaArchivesPO.setMeasureWarnMoney(archivesSaveDTO.getMeasureWarnMoney());
        areaArchivesPO.setNbonetNetImei(archivesSaveDTO.getNbonetNetImei());
        areaArchivesPO.setNormalDayDosage(archivesSaveDTO.getNormalDayDosage());
        areaArchivesPO.setPaymod(archivesSaveDTO.getPaymod());
        areaArchivesPO.setRunstate(archivesSaveDTO.getRunstate());
        areaArchivesPO.setSerialnumber(archivesSaveDTO.getSerialnumber());
        areaArchivesPO.setMeasureEquipCollect(archivesSaveDTO.getMeasureEquipCollect());
        areaArchivesPO.setSysconfigMeterModel(archivesSaveDTO.getSysconfigMeterModel());
        areaArchivesPO.setMeasureParamPrice(archivesSaveDTO.getMeasureParamPrice());
        areaArchivesPO.setMeterType(archivesSaveDTO.getMeterType());
        areaArchivesPO.setMeasureAreaOrg(archivesSaveDTO.getMeasureAreaOrg());

        areaArchivesPO.setMeasureEquipConcent(archivesSaveDTO.getMeasureEquipConcent());
        EquipConcentPO equipConcentPO = equipConcentService.getPO(
                BigDecimal.valueOf(archivesSaveDTO.getMeasureEquipConcent()).intValue());
        areaArchivesPO.setEquipmentType(equipConcentPO.getEquipmentType());
        if (SystemConsts.EquipmentTypeEnum.LORAWAN.value.equals(areaArchivesPO.getEquipmentType())) {
            if (StrUtil.isNotBlank(archivesSaveDTO.getLorawanDeveui().toLowerCase())) {
                QueryWrapper<AreaArchivesPO> queryWrapper = new QueryWrapper<>();
                String lorawanDeveui = archivesSaveDTO.getLorawanDeveui().toLowerCase();
                queryWrapper.eq("lorawan_deveui", lorawanDeveui);
                Integer count = areaArchivesPOMapper.selectCount(queryWrapper);
                if (count > 0) {
                    return 0L;
                }
                areaArchivesPO.setLorawanDeveui(lorawanDeveui);
            }
        } else if (SystemConsts.EquipmentTypeEnum.NBIOT.value.equals(areaArchivesPO.getEquipmentType())) {
            //todo 根据运营商的不同，获取相应的设备id
            if (SystemConsts.EquipmentNBType.MOBILE.value.equals(equipConcentPO.getEquipmentnbtype())) {
                areaArchivesPO.setNboneNetDeviceId(null);
            } else if (SystemConsts.EquipmentNBType.TELECOM.value.equals(equipConcentPO.getEquipmentnbtype())) {
                areaArchivesPO.setNboneNetDeviceId(null);
            } else if (SystemConsts.EquipmentNBType.UNION.value.equals(equipConcentPO.getEquipmentnbtype())) {
                areaArchivesPO.setNboneNetDeviceId(null);
            }
        }
        areaArchivesPO.setSysconfigEquipmentModel(equipConcentPO.getSysconfigEquipmentModel());

        final List<String> list = new ArrayList<String>();
        Long measureAreaOrg = areaArchivesPO.getMeasureAreaOrg();
        AreaOrganizationSaveDTO org;
        if (measureAreaOrg != null) {
            org = areaOrganizationService.getAreaOrganization(BigDecimal.valueOf(measureAreaOrg).intValue());
            while (org != null && BigDecimal.valueOf(org.getParentId()).intValue() != 0) {
                list.add(org.getName());
                org = areaOrganizationService.getAreaOrganization(BigDecimal.valueOf(org.getParentId()).intValue());
            }
            list.add(org.getName());
        }
        Collections.reverse(list);
        final StringBuffer sb = new StringBuffer();
        for (final String area : list) {
            sb.append(area);
        }
        areaArchivesPO.setOreaName(sb.toString());

        areaArchivesPO.setValveState(0);
        areaArchivesPO.setReading("0");
        areaArchivesPO.setMeterTip("0");
        areaArchivesPO.setMeterPeak("0");
        areaArchivesPO.setMeterFlat("0");
        areaArchivesPO.setMeterValley("0");

//        areaArchivesPO.setMeterReading("0");
//        areaArchivesPO.setMeterMemo();
//        areaArchivesPO.setMeterTotal();
//        areaArchivesPO.setBattery();
//        areaArchivesPO.setSnr(archivesSaveDTO.);

        areaArchivesPOMapper.insert(areaArchivesPO);
        return areaArchivesPO.getId();
    }

    @Override
    public boolean update(ArchivesSaveDTO archivesSaveDTO) {
        if (archivesSaveDTO.getCustomerName() == null ||
                StrUtil.isBlank(archivesSaveDTO.getSerialnumber())) {
            throw new MyException(ResponseCode.PARAMETER_REQUIRED);
        }

        //邮箱合法性校验，可以为空，不为空格式需符合要求
        if (StrUtil.isNotBlank(archivesSaveDTO.getCustomerEmail()) &&
                !CustomStrUtil.isEmail(archivesSaveDTO.getCustomerEmail())) {
            throw new MyException(ResponseCode.EMAIL_FORMAT_ERROR);
        }

        AreaArchivesPO areaArchivesPO = areaArchivesPOMapper.selectById(archivesSaveDTO.getId());
        if (areaArchivesPO == null || SystemConsts.BooleanEnum.TRUE.value.equals(areaArchivesPO.getIsDel())) {
            throw new MyException(ResponseCode.RECORD_NOT_EXIST);
        }

        areaArchivesPO.setId(archivesSaveDTO.getId());
        areaArchivesPO.setModifyDate(new Date());
        areaArchivesPO.setOperatorId(1L);

        areaArchivesPO.setCollectChannel(archivesSaveDTO.getCollectChannel());
        areaArchivesPO.setControlValueAddress(archivesSaveDTO.getCustomerAddress());
        areaArchivesPO.setCustomerAddress(archivesSaveDTO.getCustomerAddress());
        areaArchivesPO.setCustomerCertificateNumber(archivesSaveDTO.getCustomerCertificateNumber());
        areaArchivesPO.setCustomerCertificateType(archivesSaveDTO.getCustomerCertificateType());
        areaArchivesPO.setCustomerEmail(archivesSaveDTO.getCustomerEmail());
        areaArchivesPO.setCustomerFee(archivesSaveDTO.getCustomerFee());
        areaArchivesPO.setCustomerName(archivesSaveDTO.getCustomerName());
        areaArchivesPO.setCustomerPassword(archivesSaveDTO.getCustomerAddress());
        areaArchivesPO.setCustomerPhone(archivesSaveDTO.getCustomerPhone());
        areaArchivesPO.setCustomerSerialnumber(archivesSaveDTO.getCustomerSerialnumber());
        areaArchivesPO.setCustomerState(archivesSaveDTO.getCustomerState());
        areaArchivesPO.setCustomerTel(archivesSaveDTO.getCustomerTel());
        areaArchivesPO.setCustomerType(archivesSaveDTO.getCustomerType());
        areaArchivesPO.setCustomerUseState(archivesSaveDTO.getCustomerUseState());
        areaArchivesPO.setHouseholdNum(archivesSaveDTO.getHouseholdNum());
        areaArchivesPO.setMeasureBillingType(archivesSaveDTO.getMeasureBillingType());
        areaArchivesPO.setMeasureControlType(archivesSaveDTO.getMeasureControlType());
        areaArchivesPO.setMeasureName(archivesSaveDTO.getMeasureName());
        areaArchivesPO.setMeasureOverdraftMoney(archivesSaveDTO.getMeasureOverdraftMoney());
        areaArchivesPO.setMeasureWarnMoney(archivesSaveDTO.getMeasureWarnMoney());
        areaArchivesPO.setNbonetNetImei(archivesSaveDTO.getNbonetNetImei());
        areaArchivesPO.setNormalDayDosage(archivesSaveDTO.getNormalDayDosage());
        areaArchivesPO.setPaymod(archivesSaveDTO.getPaymod());
        areaArchivesPO.setRunstate(archivesSaveDTO.getRunstate());
        areaArchivesPO.setSerialnumber(archivesSaveDTO.getSerialnumber());
        areaArchivesPO.setMeasureEquipCollect(archivesSaveDTO.getMeasureEquipCollect());
        areaArchivesPO.setSysconfigMeterModel(archivesSaveDTO.getSysconfigMeterModel());
        areaArchivesPO.setMeasureParamPrice(archivesSaveDTO.getMeasureParamPrice());
        areaArchivesPO.setMeterType(archivesSaveDTO.getMeterType());
        areaArchivesPO.setMeasureAreaOrg(archivesSaveDTO.getMeasureAreaOrg());

        areaArchivesPO.setMeasureEquipConcent(archivesSaveDTO.getMeasureEquipConcent());
        EquipConcentPO equipConcentPO = equipConcentService.getPO(
                BigDecimal.valueOf(archivesSaveDTO.getMeasureEquipConcent()).intValue());
        areaArchivesPO.setEquipmentType(equipConcentPO.getEquipmentType());
        if (SystemConsts.EquipmentTypeEnum.LORAWAN.value.equals(areaArchivesPO.getEquipmentType())) {
            if (StrUtil.isNotBlank(archivesSaveDTO.getLorawanDeveui().toLowerCase())) {
                QueryWrapper<AreaArchivesPO> queryWrapper = new QueryWrapper<>();
                String lorawanDeveui = archivesSaveDTO.getLorawanDeveui().toLowerCase();
                queryWrapper.eq("lorawan_deveui", lorawanDeveui);
                Integer count = areaArchivesPOMapper.selectCount(queryWrapper);
                if (count > 0) {
                    return false;
                }
                areaArchivesPO.setLorawanDeveui(lorawanDeveui);
            }
        } else if (SystemConsts.EquipmentTypeEnum.NBIOT.value.equals(areaArchivesPO.getEquipmentType())) {
            //todo 根据运营商的不同，获取相应的设备id
            if (SystemConsts.EquipmentNBType.MOBILE.value.equals(equipConcentPO.getEquipmentnbtype())) {
                areaArchivesPO.setNboneNetDeviceId(null);
            } else if (SystemConsts.EquipmentNBType.TELECOM.value.equals(equipConcentPO.getEquipmentnbtype())) {
                areaArchivesPO.setNboneNetDeviceId(null);
            } else if (SystemConsts.EquipmentNBType.UNION.value.equals(equipConcentPO.getEquipmentnbtype())) {
                areaArchivesPO.setNboneNetDeviceId(null);
            }
        }
        areaArchivesPO.setSysconfigEquipmentModel(equipConcentPO.getSysconfigEquipmentModel());

        final List<String> list = new ArrayList<String>();
        Long measureAreaOrg = areaArchivesPO.getMeasureAreaOrg();
        AreaOrganizationSaveDTO org;
        if (measureAreaOrg != null) {
            org = areaOrganizationService.getAreaOrganization(BigDecimal.valueOf(measureAreaOrg).intValue());
            while (org != null && BigDecimal.valueOf(org.getParentId()).intValue() != 0) {
                list.add(org.getName());
                org = areaOrganizationService.getAreaOrganization(BigDecimal.valueOf(org.getParentId()).intValue());
            }
            list.add(org.getName());
        }
        Collections.reverse(list);
        final StringBuffer sb = new StringBuffer();
        for (final String area : list) {
            sb.append(area);
        }
        areaArchivesPO.setOreaName(sb.toString());

//        areaArchivesPO.setValveState(0);
//        areaArchivesPO.setReading("0");
//        areaArchivesPO.setMeterTip("0");
//        areaArchivesPO.setMeterPeak("0");
//        areaArchivesPO.setMeterFlat("0");
//        areaArchivesPO.setMeterValley("0");

//        areaArchivesPO.setMeterReading("0");
//        areaArchivesPO.setMeterMemo();
//        areaArchivesPO.setMeterTotal();
//        areaArchivesPO.setBattery();
//        areaArchivesPO.setSnr(archivesSaveDTO.);

        areaArchivesPOMapper.updateById(areaArchivesPO);
        return true;
    }

    @Override
    public boolean delete(List<Integer> ids) {
        if (CollUtil.isEmpty(ids)) {
            throw new MyException(ResponseCode.PARAMETER_REQUIRED);
        }

        //供应商表逻辑删除
        QueryWrapper<AreaArchivesPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        EnergyTypeUtil.injectEnergyTypeWrapper(queryWrapper);
        AreaArchivesPO areaArchivesPO = new AreaArchivesPO();
        areaArchivesPO.setIsDel(SystemConsts.BooleanEnum.TRUE.value);
        int num = areaArchivesPOMapper.update(areaArchivesPO, queryWrapper);

        return num > 0;
    }

    @Override
    public ArchivesSaveDTO getArchives(Integer id) {
        AreaArchivesPO areaArchivesPO = areaArchivesPOMapper.selectById(id);
        if (areaArchivesPO == null || SystemConsts.BooleanEnum.TRUE.value.equals(areaArchivesPO.getIsDel())) {
            throw new MyException(ResponseCode.RECORD_NOT_EXIST);
        }

        ArchivesSaveDTO archivesSaveDTO = new ArchivesSaveDTO();
        archivesSaveDTO.setId(areaArchivesPO.getId());
        archivesSaveDTO.setCustomerName(areaArchivesPO.getCustomerName());
        archivesSaveDTO.setCustomerType(areaArchivesPO.getCustomerType());
        archivesSaveDTO.setCustomerSerialnumber(areaArchivesPO.getCustomerSerialnumber());
        archivesSaveDTO.setCustomerState(areaArchivesPO.getCustomerState());
        archivesSaveDTO.setCustomerPhone(areaArchivesPO.getCustomerPhone());
        archivesSaveDTO.setCustomerTel(areaArchivesPO.getCustomerTel());
        archivesSaveDTO.setCustomerCertificateType(areaArchivesPO.getCustomerCertificateType());
        archivesSaveDTO.setCustomerCertificateNumber(areaArchivesPO.getCustomerCertificateNumber());
        archivesSaveDTO.setCustomerEmail(areaArchivesPO.getCustomerEmail());
        archivesSaveDTO.setHouseholdNum(areaArchivesPO.getHouseholdNum());
        archivesSaveDTO.setCustomerUseState(areaArchivesPO.getCustomerUseState());
        archivesSaveDTO.setCustomerFee(areaArchivesPO.getCustomerFee());
        archivesSaveDTO.setCustomerAddress(areaArchivesPO.getCustomerAddress());
        archivesSaveDTO.setNormalDayDosage(areaArchivesPO.getNormalDayDosage());
        archivesSaveDTO.setMeasureName(areaArchivesPO.getMeasureName());
        archivesSaveDTO.setPaymod(areaArchivesPO.getPaymod());
        archivesSaveDTO.setMeasureEquipConcent(areaArchivesPO.getMeasureEquipConcent());
        archivesSaveDTO.setMeasureEquipCollect(areaArchivesPO.getMeasureEquipCollect());
        archivesSaveDTO.setCollectChannel(areaArchivesPO.getCollectChannel());
        archivesSaveDTO.setMeasureBillingType(areaArchivesPO.getMeasureBillingType());
        archivesSaveDTO.setMeasureParamPrice(areaArchivesPO.getMeasureParamPrice());
        archivesSaveDTO.setMeasureControlType(areaArchivesPO.getMeasureControlType());
        archivesSaveDTO.setMeasureOverdraftMoney(areaArchivesPO.getMeasureOverdraftMoney());
        archivesSaveDTO.setMeasureWarnMoney(areaArchivesPO.getMeasureWarnMoney());
        archivesSaveDTO.setSerialnumber(areaArchivesPO.getSerialnumber());
        archivesSaveDTO.setSysconfigMeterModel(areaArchivesPO.getSysconfigMeterModel());
        archivesSaveDTO.setRunstate(areaArchivesPO.getRunstate());
        archivesSaveDTO.setLorawanDeveui(areaArchivesPO.getLorawanDeveui());
        archivesSaveDTO.setMeterType(areaArchivesPO.getMeterType());
        archivesSaveDTO.setNbonetNetImei(areaArchivesPO.getNbonetNetImei());
        archivesSaveDTO.setMeasureAreaOrg(areaArchivesPO.getMeasureAreaOrg());

        return archivesSaveDTO;
    }

    @Override
    public Map<String, List<EnumVO>> getEnums() {
        Map<String, List<EnumVO>> resultMap = new HashMap<>();

        List<EnumVO> archivesFilter = new ArrayList<>();
        for (SystemConsts.ArchivesFilter value : SystemConsts.ArchivesFilter.values()) {
            EnumVO vo = new EnumVO();
            vo.setValue(value.value);
            vo.setValueName(value.valueName);
            vo.setDesc(value.desc);
            archivesFilter.add(vo);
        }

        List<EnumVO> customerType = new ArrayList<>();
        for (SystemConsts.ArchivesCustomerTypeEnum value : SystemConsts.ArchivesCustomerTypeEnum.values()) {
            EnumVO vo = new EnumVO();
            vo.setValue(value.value);
            vo.setValueName(value.valueName);
            vo.setDesc(value.desc);
            customerType.add(vo);
        }

        List<EnumVO> customerState = new ArrayList<>();
        for (SystemConsts.ArchivesCustomerStateEnum value : SystemConsts.ArchivesCustomerStateEnum.values()) {
            EnumVO vo = new EnumVO();
            vo.setValue(value.value);
            vo.setValueName(value.valueName);
            vo.setDesc(value.desc);
            customerState.add(vo);
        }

        List<EnumVO> valveState = new ArrayList<>();
        for (SystemConsts.ValveStateEnum value : SystemConsts.ValveStateEnum.values()) {
            EnumVO vo = new EnumVO();
            vo.setValue(value.value);
            vo.setValueName(value.valueName);
            vo.setDesc(value.desc);
            valveState.add(vo);
        }

        List<EnumVO> certificate = new ArrayList<>();
        for (SystemConsts.CustomerCertificateType value : SystemConsts.CustomerCertificateType.values()) {
            EnumVO vo = new EnumVO();
            vo.setValue(value.value);
            vo.setValueName(value.valueName);
            certificate.add(vo);
        }

        List<EnumVO> enabledState = new ArrayList<>();
        for (SystemConsts.EnabledState value : SystemConsts.EnabledState.values()) {
            EnumVO vo = new EnumVO();
            vo.setValue(value.value);
            vo.setValueName(value.valueName);
            enabledState.add(vo);
        }

        List<EnumVO> payMod = new ArrayList<>();
        for (SystemConsts.PayModEnum value : SystemConsts.PayModEnum.values()) {
            EnumVO vo = new EnumVO();
            vo.setValue(value.value);
            vo.setValueName(value.valueName);
            payMod.add(vo);
        }

        List<EnumVO> collectChannel = new ArrayList<>();
        for (SystemConsts.CollectChannel value : SystemConsts.CollectChannel.values()) {
            EnumVO vo = new EnumVO();
            vo.setValue(value.value);
            vo.setValueName(value.valueName);
            vo.setDesc(value.desc);
            collectChannel.add(vo);
        }

        List<EnumVO> measureBillingType = new ArrayList<>();
        for (SystemConsts.MeasureBillingType value : SystemConsts.MeasureBillingType.values()) {
            EnumVO vo = new EnumVO();
            vo.setValue(value.value);
            vo.setValueName(value.valueName);
            measureBillingType.add(vo);
        }

        List<EnumVO> measureControlType = new ArrayList<>();
        for (SystemConsts.MeasureControlType value : SystemConsts.MeasureControlType.values()) {
            EnumVO vo = new EnumVO();
            vo.setValue(value.value);
            vo.setValueName(value.valueName);
            measureControlType.add(vo);
        }

        List<EnumVO> runState = new ArrayList<>();
        for (SystemConsts.RunStateEnum value : SystemConsts.RunStateEnum.values()) {
            EnumVO vo = new EnumVO();
            vo.setValue(value.value);
            vo.setValueName(value.valueName);
            runState.add(vo);
        }

        List<EnumVO> meterType = new ArrayList<>();
        for (SystemConsts.MeterType value : SystemConsts.MeterType.values()) {
            EnumVO vo = new EnumVO();
            vo.setValue(value.value);
            vo.setValueName(value.valueName);
            meterType.add(vo);
        }

        resultMap.put("archivesFilter", archivesFilter);
        resultMap.put("customerType", customerType);
        resultMap.put("customerState", customerState);
        resultMap.put("valveState", valveState);
        resultMap.put("certificate", certificate);
        resultMap.put("enabledState", enabledState);
        resultMap.put("payMod", payMod);
        resultMap.put("collectChannel", collectChannel);
        resultMap.put("measureBillingType", measureBillingType);
        resultMap.put("measureControlType", measureControlType);
        resultMap.put("runState", runState);
        resultMap.put("meterType", meterType);
        return resultMap;
    }
}
